package coupon

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/models/Admin"
	USER "OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type PostAddress struct {
	beego.Controller
}

func (c *PostAddress) PostAddress() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/Address/PostAddress"
	var err error

	coupon := &Admin.Coupon{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	//user:=&USER.WXUser{}
	o := orm.NewOrm()

	coupon.CouponId = c.GetString("id")

	//s := strconv.FormatInt(time.Now().Unix(), 10)
	//address.AddressId = "ADD" + s
	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = o.Read(coupon)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	if coupon.Num == 0 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "402", "已领完")
		return
	}
	sql := "select * from `w_x_user_coupons` where `w_x_user_id`=? and `coupon_id`=?"
	err = o.Raw(sql, openid, coupon.CouponId).QueryRow(&coupon)
	if err != nil && err.Error() != "<QuerySeter> no row found" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	} else if err == nil {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "401", "已领取")
		return
	}

	user := &USER.WXUser{OpenId: openid}
	m2m := o.QueryM2M(coupon, "WXUser")
	_, err = m2m.Add(user)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql = "update `coupon` set `num`=`num`-1 where `coupon_id`=? "
	_, err = o.Raw(sql, coupon.CouponId).Exec()

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
